package com.project.base.core.zookeeper;


import com.project.base.common.ZookeeperUtils;
import com.project.base.core.ICallback;

/**
 * Zookeeper事件监听器
 *
 * @author wxliyong
 */
public class ZNodeMonitor implements ICallback {

    private String znode;

    private ZNodeListener listener;

    private boolean isOver = false;

    public ZNodeMonitor(String znode, ZNodeListener listener) {
        this.znode = znode;
        this.listener = listener;
    }

    public void start() {
        ZookeeperUtils.getInstance().registerWatcher(znode, this);
    }

    public boolean isOver() {
        return isOver;
    }

    @Override
    public void call(Object obj) {
        if (obj == null || !(obj instanceof ZNodeEvent)) {
            return;
        }
        ZNodeEvent zNodeEvent = (ZNodeEvent) obj;
        if (ZNodeEvent.EventStatus.EXPIRED.equals(zNodeEvent.getStatus())) {
            listener.closing(-1);
            isOver = true;
            return;
        }
        listener.process(zNodeEvent);
        ZookeeperUtils.getInstance().registerWatcher(znode, this);
    }
}